#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// LVGL 相关头文件
#include "lvgl/lvgl.h"
#include "lv_drivers/display/fbdev.h"
#include "lv_drivers/indev/evdev.h"

// 配置常量
#define ACCOUNT_LENGTH 10
#define SERVER_IP "192.168.2.77"
#define SERVER_PORT 60000

// 用户信息结构体
struct account_info
{
    char a[ACCOUNT_LENGTH + 1];
    char user_name[30];
    char password[30];
};

struct login_info
{
    char identifier[30];
    char password[30];
};

// 在线用户链表
struct online_user
{
    char account[ACCOUNT_LENGTH + 1];
    char username[30];
    struct online_user *next;
};

// 消息结构体
struct chat_message
{
    char sender[ACCOUNT_LENGTH + 1];
    char recipient[ACCOUNT_LENGTH + 1];
    char content[256];
};

// 全局变量
int socket_fd = -1;
char current_account[ACCOUNT_LENGTH + 1] = {0};
char current_username[30] = {0};
struct online_user *online_list = NULL;

// 线程参数结构体
struct thread_args
{
    int socket_fd;
    int *is_running;
    struct online_user **online_list;
};

// 运行状态
int is_running = 1;

// 添加在线用户
void add_online_user(struct online_user **list, const char *account, const char *username)
{
    struct online_user *new_user = malloc(sizeof(struct online_user));
    if (!new_user)
        return;
    strncpy(new_user->account, account, ACCOUNT_LENGTH);
    strncpy(new_user->username, username, 29);
    new_user->next = *list;
    *list = new_user;
}

// 清空在线用户列表
void free_online_users(struct online_user *list)
{
    while (list != NULL)
    {
        struct online_user *temp = list;
        list = list->next;
        free(temp);
    }
}

// 接收服务器消息线程
void *recv_thread_func(void *arg)
{
    struct thread_args *args = (struct thread_args *)arg;
    int socket_fd = args->socket_fd;
    int *is_running = args->is_running;
    struct online_user **online_list = args->online_list;

    char buf[1024];
    while (*is_running)
    {
        memset(buf, 0, sizeof(buf));
        int ret = recv(socket_fd, buf, sizeof(buf) - 1, 0);
        if (ret <= 0)
        {
            printf("连接断开\n");
            *is_running = 0;
            break;
        }

        buf[ret] = '\0';

        // 处理登录成功响应
        if (strncmp(buf, "LOGIN_SUCCESS:", 14) == 0)
        {
            sscanf(buf + 14, "%30[^:]:%10s", current_username, current_account);
            lv_label_set_text(lv_obj_get_child(lv_scr_act(), 0), "登录成功！");
        }

        // 处理在线用户列表
        else if (strncmp(buf, "ONLINE:", 7) == 0)
        {
            char *token = strtok(buf + 7, ":");
            free_online_users(*online_list);
            *online_list = NULL;

            while (token != NULL)
            {
                char account[ACCOUNT_LENGTH + 1], username[30];
                if (sscanf(token, "%10[^,],%29[^\n]", account, username) == 2)
                    add_online_user(online_list, account, username);
                token = strtok(NULL, ":");
            }
        }

        // 私聊消息
        else if (strncmp(buf, "PRIVATE:", 8) == 0)
        {
            char sender[ACCOUNT_LENGTH + 1], message[256];
            if (sscanf(buf + 8, "%10[^:]:%255[^\n]", sender, message) == 2)
            {
                char msg[300];
                snprintf(msg, sizeof(msg), "[私聊] %s: %s", sender, message);
                lv_msgbox_add_text(lv_obj_get_child(lv_scr_act(), 1), msg);
            }
        }

        // 广播消息
        else
        {
            char msg[300];
            snprintf(msg, sizeof(msg), "[%s]", buf);
            lv_msgbox_add_text(lv_obj_get_child(lv_scr_act(), 1), msg);
        }
    }
    return NULL;
}

// 发送消息回调
void send_msg_event_cb(lv_event_t *e)
{
    lv_obj_t *ta = lv_event_get_target(e);
    const char *msg = lv_textarea_get_text(ta);
    if (strlen(msg) > 0)
    {
        send(socket_fd, msg, strlen(msg), 0);
        lv_textarea_set_text(ta, "");
    }
}

// 私聊按钮点击事件
void private_chat_event_cb(lv_event_t *e)
{
    lv_obj_t *list = lv_list_create(lv_scr_act());
    lv_obj_center(list);

    for (struct online_user *u = *online_list; u; u = u->next)
    {
        lv_obj_t *btn = lv_list_add_btn(list, NULL, u->username);
        lv_obj_add_event_cb(btn, (lv_event_cb_t)send_private_event_cb, LV_EVENT_CLICKED, (void *)u);
    }

    lv_obj_add_event_cb(list, (lv_event_cb_t)close_event_cb, LV_EVENT_DELETE, NULL);
}

void close_event_cb(lv_event_t *e)
{
    lv_obj_del(lv_event_get_current_target(e));
}

void send_private_event_cb(lv_event_t *e)
{
    struct online_user *u = (struct online_user *)lv_event_get_user_data(e);
    char msg[256];

    lv_obj_t *kb = lv_keyboard_create(lv_scr_act());
    lv_obj_t *ta = lv_textarea_create(lv_scr_act());
    lv_textarea_set_one_line(ta, true);
    lv_obj_align_to(ta, kb, LV_ALIGN_OUT_TOP_LEFT, 0, 0);
    lv_obj_add_event_cb(ta, (lv_event_cb_t)private_send_cb, LV_EVENT_READY, (void *)u);
    lv_obj_add_event_cb(ta, (lv_event_cb_t)private_send_cb, LV_EVENT_CANCEL, (void *)u);
    lv_keyboard_set_textarea(kb, ta);
}

void private_send_cb(lv_event_t *e)
{
    struct online_user *u = (struct online_user *)lv_event_get_user_data(e);
    lv_obj_t *ta = lv_event_get_target(e);
    const char *msg = lv_textarea_get_text(ta);
    char buffer[300];
    snprintf(buffer, sizeof(buffer), "PRIVATE:%s:%s", u->account, msg);
    send(socket_fd, buffer, strlen(buffer), 0);
    lv_obj_del_async(ta);
    lv_obj_del_async(lv_keyboard_get_textarea(lv_event_get_current_target(e)));
}

// 登录按钮点击事件
void login_event_cb(lv_event_t *e)
{
    struct login_info login_data;
    memset(&login_data, 0, sizeof(login_data));

    lv_obj_t *ta1 = lv_obj_get_child(lv_scr_act(), 0);
    lv_obj_t *ta2 = lv_obj_get_child(lv_scr_act(), 1);

    strcpy(login_data.identifier, lv_textarea_get_text(ta1));
    strcpy(login_data.password, lv_textarea_get_text(ta2));

    send(socket_fd, "LOGIN", 5, 0);
    send(socket_fd, &login_data, sizeof(login_data), 0);

    lv_obj_clean(lv_scr_act());

    // 创建聊天界面
    lv_obj_t *msgbox = lv_msgbox_create(lv_scr_act(), "聊天记录", "", NULL, true);
    lv_obj_set_size(msgbox, LV_PCT(100), LV_PCT(70));
    lv_obj_align(msgbox, LV_ALIGN_TOP_MID, 0, 0);

    lv_obj_t *ta = lv_textarea_create(lv_scr_act());
    lv_textarea_set_placeholder_text(ta, "输入消息...");
    lv_obj_set_width(ta, LV_PCT(100));
    lv_obj_align_to(ta, msgbox, LV_ALIGN_OUT_BOTTOM_MID, 0, 0);
    lv_obj_add_event_cb(ta, send_msg_event_cb, LV_EVENT_READY, NULL);

    lv_obj_t *btn = lv_button_create(lv_scr_act());
    lv_obj_align_to(btn, ta, LV_ALIGN_OUT_BOTTOM_LEFT, 0, 10);
    lv_obj_add_event_cb(btn, private_chat_event_cb, LV_EVENT_CLICKED, NULL);
    lv_obj_t *label = lv_label_create(btn);
    lv_label_set_text(label, "私聊");

    lv_obj_t *btn2 = lv_button_create(lv_scr_act());
    lv_obj_align_to(btn2, btn, LV_ALIGN_OUT_RIGHT_MID, 10, 0);
    lv_label_set_text(lv_label_create(btn2), "刷新列表");
    lv_obj_add_event_cb(btn2, (lv_event_cb_t)refresh_list_event_cb, LV_EVENT_CLICKED, NULL);
}

void refresh_list_event_cb(lv_event_t *e)
{
    send(socket_fd, "LIST", 4, 0);
}

// 注册按钮点击事件
void register_event_cb(lv_event_t *e)
{
    struct account_info acc_info;
    memset(&acc_info, 0, sizeof(acc_info));
    send(socket_fd, "REGISTER", 8, 0);
    recv(socket_fd, acc_info.a, ACCOUNT_LENGTH + 1, 0);

    // 模拟填写用户名密码
    strcpy(acc_info.user_name, "testuser");
    strcpy(acc_info.password, "123456");
    send(socket_fd, &acc_info, sizeof(acc_info), 0);

    char response[1024];
    recv(socket_fd, response, sizeof(response), 0);
    printf("%s\n", response);
}

// 主函数：UI 初始化 + 网络连接 + 启动接收线程
int main()
{
    // LVGL 初始化
    lv_init();
    fbdev_init();
    static lv_color_t buf[480 * 1024];
    static lv_disp_draw_buf_t disp_buf;
    lv_disp_draw_buf_init(&disp_buf, buf, NULL, 480 * 1024);

    static lv_disp_drv_t disp_drv;
    lv_disp_drv_init(&disp_drv);
    disp_drv.draw_buf = &disp_buf;
    disp_drv.flush_cb = fbdev_flush;
    disp_drv.hor_res = 800;
    disp_drv.ver_res = 480;
    lv_disp_drv_register(&disp_drv);

    evdev_init();
    static lv_indev_drv_t indev_drv;
    lv_indev_drv_init(&indev_drv);
    indev_drv.type = LV_INDEV_TYPE_POINTER;
    indev_drv.read_cb = evdev_read;
    lv_indev_drv_register(&indev_drv);

    // 创建套接字
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server_addr = {
        .sin_family = AF_INET,
        .sin_port = htons(SERVER_PORT),
        .sin_addr.s_addr = inet_addr(SERVER_IP)};

    connect(socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));

    // 登录界面
    lv_obj_t *ta1 = lv_textarea_create(lv_scr_act());
    lv_textarea_set_placeholder_text(ta1, "请输入用户名或账号");
    lv_obj_align(ta1, LV_ALIGN_CENTER, 0, -40);

    lv_obj_t *ta2 = lv_textarea_create(lv_scr_act());
    lv_textarea_set_placeholder_text(ta2, "请输入密码");
    lv_obj_align(ta2, LV_ALIGN_CENTER, 0, 0);

    lv_obj_t *btn_login = lv_button_create(lv_scr_act());
    lv_obj_align(btn_login, LV_ALIGN_CENTER, 0, 40);
    lv_obj_add_event_cb(btn_login, login_event_cb, LV_EVENT_CLICKED, NULL);
    lv_label_set_text(lv_label_create(btn_login), "登录");

    lv_obj_t *btn_register = lv_button_create(lv_scr_act());
    lv_obj_align(btn_register, LV_ALIGN_CENTER, 0, 80);
    lv_obj_add_event_cb(btn_register, register_event_cb, LV_EVENT_CLICKED, NULL);
    lv_label_set_text(lv_label_create(btn_register), "注册");

    // 创建线程接收消息
    pthread_t recv_thread;
    struct thread_args args = {.socket_fd = socket_fd, .is_running = &is_running, .online_list = &online_list};
    pthread_create(&recv_thread, NULL, recv_thread_func, &args);

    // LVGL 主循环
    while (1)
    {
        lv_timer_handler();
        usleep(5000);
    }

    close(socket_fd);
    return 0;
}